import React, { useEffect, useState } from 'react';
import TargetActivity from '@/components/TargetActivity';
import ActivityMessage from '@/components/TargetActivity/ActivityMessage';
import { IActivity } from '@/ts/core';
import { Resizable } from 'devextreme-react';
import useCtrlUpdate from '@/hooks/useCtrlUpdate';
import useAsyncLoad from '@/hooks/useAsyncLoad';
import { Spin, Button } from 'antd';
import { useMedia } from 'react-use';
import { command } from '@/ts/base';
import BannerImg from '../../Common/BannerImg';
import { ICompany, IBelong } from '@/ts/core';
import orgCtrl from '@/ts/controller';
import SwitchSpace from '../../Common/switchSpace';
import { LoadBanner } from '../../Common/bannerDefaultConfig';
import { FileItemShare } from '@/ts/base/model';
import './index.less';

interface IBanner {
  activity: FileItemShare[];
  workbench: FileItemShare[];
}
const GroupActivityItem: React.FC<{ activity: IActivity }> = ({ activity }) => {
  const [key] = useCtrlUpdate(activity);
  const [labels, setLabels] = useState<string[]>([]);
  const isWide = useMedia('(min-width: 1000px)');
  const [loaded] = useAsyncLoad(() => activity.load(10), [activity]);
  const [current, setCurrent] = useState<IActivity>(activity);
  const [checkData, setCheckData] = useState<any[]>([]);
  const [bannerImg, setBannerImg] = useState<any[]>([]);
  const [target, setTarget] = useState<IBelong>();
  useEffect(() => {
    orgCtrl.user.cacheObj.get('dynamic').then((res: any) => {
      if (res != undefined) {
        const activList = activity.activitys
          .filter((it) => it.name !== '全部')
          .filter((item) => item.activityList.length > 0);
        let resIds = res.map((item: any) => item.id);
        let newArr = activList.filter((item) => resIds.includes(item.id));
        setCheckData([...newArr]);
        getActiveImg(res);
      } else {
        const activList = activity.activitys
          .filter((it) => it.name !== '全部')
          .filter((item) => item.activityList.length > 0);
        setCheckData(activList);
      }
    });
  }, []);

  const getActiveImg = async (active: any[]) => {
    let banner: IBanner | undefined;
    let company: ICompany | undefined;
    if (active.length === 1) {
      company = orgCtrl.user.companys.find((item) => item.id === active[0].id);
    }
    if (company) {
      banner = await company.cacheObj.get<IBanner>('banner');
      setTarget(company);
    } else {
      banner = await orgCtrl.user.cacheObj.get<IBanner>('banner');
      setTarget(orgCtrl.user);
    }
    if (banner && banner.activity && banner.activity.length) {
      setBannerImg(banner.activity);
    } else {
      const defaultImgs = LoadBanner('activity');
      setBannerImg(defaultImgs ?? []);
    }
  };

  const FileOpen = (app: IActivity[]) => {
    let labels: string[] = [];
    app.map((item) => {
      labels.push(item.name);
    });
    setLabels(labels);
    const activList = activity.activitys.filter((item) => item.activityList.length > 0);
    if (labels.length > 0) {
      const result = activList
        .filter((it) => it.name !== '全部')
        .filter((it: IActivity) => labels.includes(it.name));
      setCurrent(result[0]);
    } else {
      setCurrent(activList[0]);
    }
    let arr: any = [];
    app.forEach((element) => {
      arr.push(element.metadata);
    });
    orgCtrl.user.cacheObj.set('dynamic', arr).then((res: boolean) => {
      if (res === true) {
        setCheckData(app);
      }
    });
  };
  const loadMenus = React.useCallback(
    (checkData: IActivity[]) => {
      const [activityList, setActivityList] = useState<IActivity[]>([]);
      useEffect(() => {
        var arr =
          checkData.length === 0
            ? activity.activitys.filter((item) => item.activityList.length > 0)
            : checkData.filter((item) => item.activityList.length > 0);
        arr.sort(
          (a, b) =>
            new Date(b.activityList[0].metadata.createTime).getTime() -
            new Date(a.activityList[0].metadata.createTime).getTime(),
        );
        setActivityList(arr);
        getActiveImg(checkData);
      }, [loaded, activity, labels, current, checkData]);

      if (!loaded || !isWide) return <></>;
      return (
        <div className="groupContainer">
          <Resizable handles={'right'}>
            <div className="publish">
              <span style={{ fontSize: 16, lineHeight: '24px', fontWeight: 600 }}>
                动态列表
              </span>
              <Button
                type="link"
                onClick={() => {
                  command.emitter(
                    'executor',
                    'pubActivity',
                    activityList.find((it) => it.name === '全部'),
                  );
                }}>
                发布个人动态
              </Button>
            </div>
            <div className={'groupList'}>
              {activityList.map((item) => {
                if (item.activityList.length > 0) {
                  const _name = item.id === current.id ? 'selected' : 'item';
                  return (
                    <div
                      className={`groupList-${_name}`}
                      key={item.key}
                      onClick={(e) => {
                        e.stopPropagation();
                        setCurrent(item);
                      }}>
                      <ActivityMessage
                        key={item.key}
                        item={item.activityList[0]}
                        activity={item}
                        hideResource
                      />
                    </div>
                  );
                }
              })}
            </div>
          </Resizable>
        </div>
      );
    },
    [loaded, current, activity, key, isWide],
  );

  const loadContext = React.useCallback(() => {
    if (!loaded) return <></>;
    return (
      <div className={'loadContext'}>
        <TargetActivity
          height={'calc(100vh - 110px)'}
          activity={current}
          title={current.name + '动态'}></TargetActivity>
      </div>
    );
  }, [loaded, current]);

  return (
    <div className={'activityContent'}>
      <Spin tip="加载中,请稍后..." size="large" spinning={!loaded} delay={100}>
        <div style={{ padding: '12px', marginLeft: 8 }}>
          <SwitchSpace
            content={activity.activitys.filter((item) => item.activityList.length > 0)}
            typeName={'动态'}
            selectFiles={checkData}
            searchText={'dynamic'}
            selectType={2}
            onChange={(res: ICompany[]) => FileOpen(res)}></SwitchSpace>
        </div>
        {bannerImg.length > 0 && (
          <div style={{ width: '100%', marginLeft: 20 }}>
            <BannerImg
              bannerImg={bannerImg}
              bannerkey="activity"
              target={target as IBelong}></BannerImg>
          </div>
        )}
        <div className="groupCtx">
          {loadMenus(checkData)}
          {loadContext()}
        </div>
      </Spin>
    </div>
  );
};

export default GroupActivityItem;
